package controller

import (
	"encoding/json"
	"fmt"
	"gin/common"
	"gin/response"
	"gin/util"
	"github.com/gin-gonic/gin"
)

type Province struct {
	Id    int
	Level int
	Name  string
}

// GetProvince 省份
func GetProvince(ctx *gin.Context) {
	redisDB := common.GetRedis()
	list, err := redisDB.Get("province").Result()
	if err != nil {
		fmt.Println(err.Error())
	}
	var provinceList []Province
	if list != "" {
		res, err := redisDB.Get("province").Result()
		if err != nil {
			fmt.Println(err.Error())
		}
		if err := json.Unmarshal([]byte(res), &provinceList); err != nil {
			fmt.Println("Unmarshal goods", err.Error())
			return
		}
	} else {
		db := common.GetDB()
		db.Table("cat_meal_region").Where("level =1").Find(&provinceList)
		data, err := json.Marshal(provinceList)
		if err != nil {
			fmt.Println(err)
		}
		redisDB.Set("province", string(data), 0)
	}
	response.Success(ctx, gin.H{"list": provinceList}, "success")
}

// GetChild 城市.县区下级
func GetChild(ctx *gin.Context) {
	pid := ctx.Query("pid")
	var provinceList []Province
	db := common.GetDB()
	db.Table("cat_meal_region").Where("pid = ?", pid).First(&provinceList)
	response.Success(ctx, gin.H{"list": provinceList}, "success")
}

type CatMealPage struct {
	Id      int `gorm:"column:id"`
	DateAdd string
	Title   string
	Content string
}

// GetPage 文章
func GetPage(ctx *gin.Context) {
	var page []CatMealPage
	db := common.GetDB()
	db.Table("cat_meal_page").Find(&page)
	response.Success(ctx, gin.H{"list": page}, "success")
}

// GetNotice 店铺公告
func GetNotice(ctx *gin.Context) {
	var page []CatMealPage
	db := common.GetDB()
	shopId := ctx.Query("shopId")
	if len(shopId) == 0 {
		response.Fail(ctx, gin.H{}, "缺少店铺标识")
		return
	}
	db.Table("cat_meal_notice").Where("isShow=1").Where("shopId=?", shopId).First(&page)
	response.Success(ctx, gin.H{"info": page}, "success")
}

type BannerStruct struct {
	Id    int    `gorm:"column:id"`
	Title string `gorm:"column:title"`
	Pic   string `gorm:"column:picUrl"`
}

// GetBanner 店铺banner
func GetBanner(ctx *gin.Context) {
	var page []BannerStruct
	db := common.GetDB()
	shopId := ctx.Query("shopId")
	if len(shopId) == 0 {
		response.Fail(ctx, gin.H{}, "缺少店铺标识")
		return
	}
	db.Table("cat_meal_banner").Where("status=1 and shopId=?", shopId).Find(&page)
	response.Success(ctx, gin.H{"list": page}, "success")
}

// GetLocation 通过当前IP获取城市
func GetLocation(ctx *gin.Context) {
	ip := ctx.PostForm("ip")
	if len(ip) == 0 {
		ip = util.GetLocalIP()
	}
	content := common.CurlGet("https://apis.map.qq.com/ws/location/v1/ip?ip=" + ip + "&key=BNUBZ-BLAK4-HDPUG-XTGHX-6M4NV-MZFVX")
	var jsonArr map[string]interface{}
	err := json.Unmarshal([]byte(content), &jsonArr)
	if err != nil {
		return
	}
	fmt.Printf("%T", jsonArr["status"].(float64))
	if jsonArr["status"].(float64) != 0 {
		response.Fail(ctx, gin.H{}, jsonArr["message"].(string))
		return
	}
	response.Success(ctx, gin.H{"result": jsonArr["result"]}, "success")
}
